﻿using System;
using System.Xml;

using octalforty.Syndication.Core.Internal;

namespace octalforty.Syndication.Core
{
    /// <summary>
    /// Provides a base class for syndication managers.
    /// </summary>
    public abstract class SyndicationManagerBase : ISyndicationManager
    {
        #region Private Member Variables
        private IAggregator rootAggregator = new NullAggregator();
        #endregion

        /// <summary>
        /// Initializes a new instance of <see cref="SyndicationManagerBase"/> class.
        /// </summary>
        protected SyndicationManagerBase()
        {
        }

        /// <summary>
        /// Adds a <paramref name="aggregator"/> to the end of aggregators chain.
        /// </summary>
        /// <param name="aggregator"></param>
        protected void AddAggregator(IAggregator aggregator)
        {
            AddAggregator(rootAggregator, aggregator);
        }

        #region ISyndicationManager Members
        /// <summary>
        /// Aggregates <paramref name="feedDocument"/> into <see cref="ISyndicationFeed"/>.
        /// </summary>
        /// <param name="feedDocument"></param>
        public virtual ISyndicationFeed Aggregate(XmlDocument feedDocument)
        {
            ISyndicationFeed syndicationFeed = null;
            rootAggregator.Aggregate(feedDocument, ref syndicationFeed);

            return syndicationFeed;
        }

        /// <summary>
        /// Syndicates <paramref name="syndicationFeed"/> into <see cref="XmlDocument"/>.
        /// </summary>
        /// <param name="syndicationFeed"></param>
        /// <returns></returns>
        public XmlDocument Syndicate(ISyndicationFeed syndicationFeed)
        {
            throw new NotImplementedException();
        }
        #endregion

        /// <summary>
        /// Recursively adds <paramref name="aggregator"/> to the end of the chain
        /// represented by <paramref name="parentAggregator"/>.
        /// </summary>
        /// <param name="parentAggregator"></param>
        /// <param name="aggregator"></param>
        private static void AddAggregator(IAggregator parentAggregator, IAggregator aggregator)
        {
            if(parentAggregator.NextAggregator == null)
                parentAggregator.NextAggregator = aggregator;
            else 
                AddAggregator(parentAggregator.NextAggregator, aggregator);
        }
    }
}
